<template>
  <div>
    <el-form class="m7-form" :model="form" :rules="ruleSpareParts" ref="form" label-position="top">
      <el-form-item label="触发器名称" prop="name">
        <el-input
          v-model.trim="form.name"
          size="mini"
          placeholder="请输入"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          :autosize="{ minRows: 2, maxRows: 6}"
          type="textarea"
          v-model.trim="form.remark"
          size="mini"
          placeholder="请输入"
        >
        </el-input>
      </el-form-item>
      <el-form-item
        label="选择触发事件"
        prop="triggerEvent"
      >
        <el-select
          v-model="form.triggerEvent"
          placeholder="请选择"
          filterable
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="选择生效范围"
        prop="takeEffectType"
      >
      <el-radio-group v-model="form.takeEffectType">
        <el-radio-button :label="1">全局生效</el-radio-button>
        <el-radio-button :label="2">选择节点</el-radio-button>
      </el-radio-group>
      <el-select
        v-if="form.takeEffectType === 2"
        v-model="form.nodeList"
        multiple
        collapse-tags
        placeholder="请选择"
        filterable
      >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="选择触发条件"
        prop="filters"
      >
        <conditionForm
          :fieldsList="filterFieldList"
          :conditonList="form.filters"
          class="condition"
          type="filter"
        >
        </conditionForm>
      </el-form-item>
      <el-form-item
        label="选择执行动作"
        prop="triggerEvent"
      >
        <el-select
          v-model="form.actionType"
          placeholder="请选择"
          filterable
        >
          <el-option label="数据推送" :value="1"></el-option>
          <el-option label="短信通知" :value="2"></el-option>
        </el-select>
        <div v-if="form.actionType === 2" class="sms-block">
          <div style="display: flex">
            <div class="label">发送对象：</div>
            <optionalScope
            style="flex: 1;line-height: 32px;"
            :isCheckbox="true"
            :tabs="tabs"
            :value="form.smsTarget">
          </optionalScope>
          </div>
          <div class="msg-templ">
            <el-select
              style="margin-right: 12px"
              v-model="form.smsSignId"
              placeholder="选择签名"
              filterable
            >
              <el-option
                v-for="item in smsSignList"
                :key="item.id"
                :label="item.displayName"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="form.smsTemplateId"
              placeholder="选择模版"
              filterable
            >
              <el-option
                v-for="item in smsTemplList"
                :key="item.id"
                :label="item.displayName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <div class="sms-text" v-if="form.actionType === 2">
            <template v-if="getSmsSignMap[form.smsSignId]">【{{getSmsSignMap[form.smsSignId].displayName}}】</template>
            <template v-if="getSmsTemplMap[form.smsTemplateId]">{{getSmsTemplMap[form.smsTemplateId].content}}</template>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        v-if="form.actionType === 1"
        label="服务器地址"
        prop="pushUrl"
      >
        <el-input
          :autosize="{ minRows: 2, maxRows: 6}"
          v-model.trim="form.pushUrl"
          type="textarea"
          size="mini"
          placeholder="请输入"
        >
        </el-input>
        <div style="margin-top: 16px;font-size: 12px;margin-bottom: 10px">推送数据示例</div>
        <codemirror :value="codeValue" :options="options1" class="common-code"></codemirror>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Ref } from 'vue-property-decorator'
import conditionForm from '@/afterSales/components/conditionFilter/conditionForm.vue';
import { busConfigStore } from '@/afterSales/views/config/serviceConfig/store/busConfigStore';
import { commonAction } from '@/utils/common';
import { codemirror } from 'vue-codemirror';
import 'codemirror/lib/codemirror.css';
import optionalScope from '@/afterSales/views/config/serviceConfig/components/optionalScope.vue'
import 'codemirror/addon/scroll/simplescrollbars.css';
import 'codemirror/addon/scroll/simplescrollbars';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/markdown/markdown';
import { CommonModule } from '@/store/modules/common'
import 'codemirror/mode/http/http';
import 'codemirror/addon/runmode/colorize.js';
interface Form {
 smsTarget: {
    diy: string[]
    user: string[]
  },
  smsTemplateId?: string,
  smsSignId?: string,
  actionType: number,
  remark: string,
  nodeList?: any
  id?: string
  takeEffectType: number
  filters: any
  triggerEvent: number
  name: string,
  pushUrl: string
}
@Component({
  name: 'addOrEditTrigger',
  components: {
    optionalScope,
    conditionForm,
    codemirror
  }
})
export default class SparePartsAddOrEdit extends Vue {
  @Prop({ default: () => [] }) private smsSignList
  @Prop({ default: () => [] }) private smsTemplList
  @Prop() private id!: string
  private list = []
  private codeValue = `{
    "region_gkmz_1649215883158":["150000","150500","150523"],
    "department_fxh4_1648621335337":"10000795",
    "department_fxh4_1648621335337Name":"售后云测试",
    "modelId":"6243b24e0c3be83ce35e43f2",
    "triggerName":"name",
    "joinList":["6216128cc5a6d200127fa499"],
    "orderStatus":20,
    "createUserName":"60001Name",
    "source":2,
    "region_gkmz_1649215883158Name":["内蒙古自治区","通辽市","开鲁县"],
    "number_4MqW_1649215873158":"3.00",
    "activityId":"Activity_1462spe",
    "ass_table_spare_aNaF_1649315461638":[],
    "orderStatusName":"待处理",
    "estimateStatus":1,
    "joinListName":"60001Name",
    "id":"626218b5ec3f022bcab47eb9",
    "text_PjgE_1648603732207":"abc",
    "cascade_select_hBPu_1649215879382Name":"1/11",
    "orderNo":"YYX2022042200001",
    "updateUserName":"60001Name",
    "triggerId":"abc",
    "activityName":"完成",
    "assignType":1,
    "updateUser":"6216128cc5a6d200127fa499",
    "updateTime":"2022-05-05 16:51:12",
    "eventUniqueId":"b377a296e0d049dd9d601f0a9dc9ee15",
    "version":1651740672321,
    "cascade_select_hBPu_1649215879382":["0b407320b55a11ecb7aabd5aff6848fa","1274c790b55a11ecb7aabd5aff6848fa"],
    "master":"6216128cc5a6d200127fa499",
    "pushType":"SALE_ORDER_PUSH",
    "accountId":"2100147",
    "createTime":"2022-04-22 10:53:41",
    "multi_text_Ycot_1649215845417":"multi text",
    "createUser":"6216128cc5a6d200127fa499",
    "triggerEvent":"工单完成",
    "sourceName":"WEB端",
    "orderCategory":"yyx测试",
    "masterName":"60001Name"
  }`

  private get getSmsTemplMap () {
    const obj = {};
    this.smsTemplList.map((item) => {
      obj[item.id] = item;
    });
    return obj;
  }

  private get getSmsSignMap () {
    const obj = {};
    this.smsSignList.map((item) => {
      obj[item.id] = item;
    });
    return obj;
  }

  private get tabs () {
    return [
      {
        name: '成员',
        type: 'user',
        list: this.userList,
        listMap: (CommonModule as any).publicCache.userListObj,
        defaultProps: { id: '_id', name: 'name' }
      },
      {
        name: '动态',
        type: 'diy',
        list: this.dynamicScopeList,
        listMap: this.dynamicScopeMap,
        defaultProps: { id: 'businessId', name: 'name' }
      }
    ]
  }

  private get dynamicScopeMap () {
    const obj = {}
    this.dynamicScopeList.forEach((item) => {
      obj[item.businessId] = item
    })
    return obj
  }

  private get dynamicScopeList () {
    return [
      { businessId: 'master', name: '工单-当前处理人' },
      { businessId: 'lastActivityMaster', name: '工单-上一节点处理人' },
      { businessId: 'createUser', name: '工单-工单创建人' },
      { businessId: 'candidates', name: '工单-可领取人' },
      { businessId: 'contactor', name: '客户-联系人' },
      { businessId: 'customer', name: '客户-手机号码' }
    ]
  }

  private get userMap () {
    return (CommonModule as any).publicCache.userListObj
  }

  private get options1 () {
    return {
      value: '',
      tabSize: 2,
      mode: 'json',
      matchBrackets: true,
      lineNumbers: false,
      lineWrapping: 'wrap',
      line: true,
      addModeClass: true,
      forceBreak: true,
      readOnly: true,
      showCursorWhenSelecting: true,
      theme: 'default'
    };
  }

  private options = Object.freeze([
    {
      label: '工单进入节点',
      value: 1
    },
    {
      label: '工单离开节点',
      value: 2
    },
    {
      label: '工单终止',
      value: 3
    },
    {
      label: '工单完成',
      value: 4
    },
    {
      label: '工单被转派',
      value: 5
    },
    {
      label: '工单被领取',
      value: 6
    },
    {
      label: '工单被催办',
      value: 7
    }
  ])

  private $message: any
  private $route: any;

  private get userList () {
    return (CommonModule as any).publicCache.userList.map(v => ({ name: `${v.agentName} 【${v.agentNumber}】`, _id: v._id }))
  }

  private get filterFieldList () {
    return busConfigStore.list.filter(item => {
      return ['group'].indexOf(item.fieldType) === -1 && item.isSystem === 0
    })
  }

  public form: Form = {
    smsTarget: {
      diy: [],
      user: []
    },
    smsTemplateId: '',
    smsSignId: '',
    actionType: 1,
    remark: '',
    nodeList: [],
    takeEffectType: 1,
    filters: [],
    triggerEvent: 1,
    name: '',
    pushUrl: ''
  }

  public saveConfirm () {
    (this.$refs as any).form.validate((valid) => {
      if (valid) {
        if (this.form.actionType === 2) {
          if (!this.form.smsTarget.user.length && !this.form.smsTarget.diy.length) {
            this.$message.error('发送对象不能为空')
            return false
          } else if (!this.form.smsSignId) {
            this.$message.error('签名不能为空')
            return false
          } else if (!this.form.smsTemplateId) {
            this.$message.error('模板不能为空')
            return false
          }
        }
        const params = Object.assign({}, this.form, {
          modelId: this.$route.params.businessId
        })
        commonAction({ url: `/server-work/action/trigger/order/config/${this.form.id ? 'update' : 'insert'}`, method: 'post', data: params }).then(res => {
          if (res.success) {
            this.$message.success('成功！')
            this.$emit('success')
          }
        })
      } else {
        return false;
      }
    });
  }

  public init (data: Form) {
    if ((this.$refs as any).form) {
      (this.$refs as any).form.clearValidate()
    }
    const { actionType, smsTarget, smsTemplateId, smsSignId, remark, id, takeEffectType, filters, triggerEvent, name, pushUrl, nodeList } = data
    if (data.id) {
      this.form = { smsTarget, actionType, remark, id, smsTemplateId, smsSignId, takeEffectType, filters, triggerEvent, name, pushUrl, nodeList }
      this.$set(this.form, 'smsTarget', smsTarget || { diy: [], user: [] })
    } else {
      this.form = {
        smsTarget: {
          diy: [],
          user: []
        },
        smsTemplateId: '',
        smsSignId: '',
        actionType: 1,
        remark: '',
        takeEffectType: 1,
        filters: [],
        nodeList: [],
        triggerEvent: 1,
        name: '',
        pushUrl: ''
      }
    }
  }

  private ruleSpareParts: object = {
    triggerEvent: [{ required: true, message: '请选择生效范围', trigger: 'change' }],
    name: [{ required: true, message: '请输入触发器名称', trigger: 'blur' }],
    pushUrl: [{ required: true, message: '请输入服务器地址', trigger: 'blur' }]
  }

  private fetchNodeList () {
    commonAction({ url: '/server-flow/action/definition/userTask?modelId=' + this.$route.params.businessId, method: 'get' }).then(res => {
      if (res.success) {
        this.list = res.data || []
      }
    })
  }

  private beforeMount () {
    this.fetchNodeList()
  }
}
</script>

<style lang="stylus" scoped>
.sms-block
  background: #FBFBFB;
  border-radius: 4px;
  padding: 16px;
.sms-text {
  font-weight: 400;
  font-size: 12px;
  line-height: 18px;
  margin-top: 8px;
}
.msg-templ {
  display: flex;
}
/deep/.CodeMirror {
  background: #f9f9f9;
  .CodeMirror-line {
    font-size: 12px
  }
}
.varField {
  position: absolute;
  top: -48px;
  right: 0px;
}
.el-select
  width 100%
.label {
  font-size: 12px;
  color: #303753;
}
</style>
